<?php

class AddSponsor extends DataExtension implements PermissionProvider {
    private static $casting = array(
        'TotalSponsorDirectDownline' => 'Int',
        'TotalSponsorGroupDownline' => 'Int'
    );
	
	function validate(ValidationResult $validationResult) {
		if($this->owner->hasField('SetSponsorUsername')){
			$current_sponsor = Sponsor::get()->filter('MemberID', $this->owner->ID)->filter('ParentID', Distributor::get_id_by_username($this->owner->SetSponsorUsername))->count();
			if(!$current_sponsor){
				$sponsor = Sponsor::get()->filter('Member.Username', $this->owner->SetSponsorUsername)->first();
				if(!$sponsor){
					$subvalid = new ValidationResult();
	        		$subvalid->error(_t('AddSponsor.INVALID_SPONSOR_USERNAME', 'Invalid sponsor username'), "INVALID_SPONSOR_USERNAME");
	        		$validationResult->combineAnd($subvalid);
				}
				else if($this->owner->SetSponsorUsername == $this->owner->Username){
					$subvalid = new ValidationResult();
	        		$subvalid->error(_t('AddSponsor.INVALID_SPONSOR_OWNSELF', 'Unable to sponsor ownself'), "INVALID_SPONSOR_OWNSELF");
	        		$validationResult->combineAnd($subvalid);
				}
				else if($this->owner->Placement()->ID){
					$obj = Placement::get()->find('MemberID', $sponsor->MemberID);
					$checkPlacement = Placement::get()
		        	->filter('NLeft:GreaterThanOrEqual', (int)$obj->NLeft)
		        	->filter('NRight:LessThanOrEqual', (int)$obj->NRight)
					->filter('MemberID', (int)$this->owner->Placement()->ID)->count();
					if(!$checkPlacement){
						$subvalid = new ValidationResult();
	            		$subvalid->error(_t('AddSponsor.SPONSOR_NOT_MATCH', 'Sponsor is not match with the placement'), "SPONSOR_NOT_MATCH");
	            		$validationResult->combineAnd($subvalid);
					}
				}
			}
		}
        
        return $validationResult;
    }
    
    function updateCMSFields(FieldList $fields){
        if(!$this->owner->exists()){
            $fields->insertAfter(SponsorField::create('SetSponsorUsername', _t('AddSponsor.SPONSOR_USERNAME', 'Sponsor Username')), 'Username');
        }
        else{
        	if(Permission::check('CHANGE_Sponsor')){
        		$fields->insertAfter(SponsorField::create('SetSponsorUsername', _t('AddSponsor.SPONSOR_USERNAME', 'Sponsor Username'), $this->owner->Sponsor()->Username), 'Username');
        	}
			else{
            	$fields->insertAfter($sponsor = ReadonlyField::create('SponsorUsername', _t('AddSponsor.SPONSOR_USERNAME', 'Sponsor Username'), sprintf('%s - %s', $this->owner->Sponsor()->Username, $this->owner->Sponsor()->getName())), 'Username');
				$sponsor->setIncludeHiddenField(true);
			}
        }
    }
    
    function onAfterWrite(){
    	if($this->owner->hasField('SetSponsorUsername')){
	        $root_username = Sponsor::get_root_username();
	        $sponsor = Sponsor::get()->find('MemberID', $this->owner->ID);
			if(!$sponsor){
				$sponsor = Sponsor::create()->setField('MemberID', $this->owner->ID);
			}
			
	        if($sponsor->Parent()->Username != $this->owner->SetSponsorUsername && $this->owner->Username != $root_username){
	            $sponsor->setSponsor($this->owner->SetSponsorUsername);
	            $sponsor->write();
	        }
		}
    }
    
    function Sponsor(){
		if($this->owner->SetSponsorUsername){
			$obj = Sponsor::get()->filter('Member.Username', $this->owner->SetSponsorUsername)->first();
			return $obj ? $obj->Member() : Member::create();
		}
		
		$sponsor = Sponsor::get()->find('MemberID', $this->owner->ID);
        return ($sponsor && $sponsor->ParentID) ? $sponsor->Parent()->Member() : Member::create();
    }
    
    function getTotalSponsorDirectDownline(){
        $sponsor = Sponsor::get()->find('MemberID', $this->owner->ID);
        return ($sponsor) ? $sponsor->TotalDirectDownline : 0;
    }
    
    function getTotalSponsorGroupDownline(){
        $sponsor = Sponsor::get()->find('MemberID', $this->owner->ID);
        return ($sponsor) ? $sponsor->TotalGroupDownline : 0;
    }
	
	public function providePermissions() {
        return array(
            'CHANGE_Sponsor' => array(
                'name' => _t('AddSponsor.PERMISSION_CHANGE_SPONSOR', 'Allow change sponsor'),
                'category' => _t('AddSponsor.PERMISSIONS_CATEGORY', 'Network')
            )
        );
    }
}
